#include "spdlog/spdlog.h"

#include "http_conn.hpp"
#include "protocol/http/http_define.h"
using namespace mms;

HttpConn::HttpConn(TcpSocketHandler * handler, boost::asio::ip::tcp::socket sock, ThreadWorker * worker):TcpSocket(handler,std::move(sock),worker)
{
    buf_ = std::make_unique<char[]>(HTTP_MAX_BUF);
}

HttpConn::HttpConn(TcpSocketHandler* handler, ThreadWorker* worker):
    TcpSocket(handler, worker)
{

}

HttpConn::~HttpConn()
{
    spdlog::info("destroy httpconn");
}

boost::asio::awaitable<void> HttpConn::cycle_recv(const std::function<boost::asio::awaitable<std::pair<bool, int32_t>>(const char* buf, int32_t len)>& recv_handler)
{
   bool cont = true;
   int32_t consumed = 0;
   do{
        std::tie(cont,consumed) = co_await recv_handler((const char*)buf_.get(), buf_size_);
        if(consumed < 0){
            close();
            co_return;
        }else if(consumed == 0){
            if(HTTP_MAX_BUF - buf_size_ <= 0){
                close();
                co_return;
            }
            auto recv_size = co_await recv_some((uint8_t*)buf_.get() + buf_size_,
            HTTP_MAX_BUF - buf_size_);
            if(recv_size < 0){
                break;
            }
            buf_size_ += recv_size;
        }else {
            buf_size_ -= consumed;
            memmove((void*)buf_.get(), (void*)(buf_.get() + consumed), buf_size_);
            if(!cont){
                break;
            }
        }
   }while(cont && buf_size_ > 0);
   co_return;
}
